package com.gancp.controller;

import com.gancp.Exception.BaseServiceException;
import com.gancp.common.constants.Constants;
import com.gancp.common.response.ApiResult;
import com.gancp.controller.base.BaseController;
import com.gancp.entity.UserInfo;
import com.gancp.service.UserInfoService;
import com.gancp.vo.UserInfoVo;
import jdk.nashorn.internal.runtime.ECMAException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;

/**
 * @Author gancp
 * @Date 时间被黑洞吸走了
 * @Descripition 登录
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class LoginController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResult login(@RequestBody UserInfoVo userInfoVo) {
        ApiResult apiResult = new ApiResult();
        try {
            String data = userInfoVo.getData();
            String key = userInfoVo.getKey();
            if (StringUtils.isBlank( data ) || StringUtils.isBlank( key )) {
                throw new BaseServiceException( "参数校验失败" );
            }
            String result = userInfoService.login( data, key );
            apiResult.setResultData( result );
            apiResult.setMessage( "登录成功" );
        } catch (BaseServiceException e) {
            apiResult.setState( e.getstatuscode() );
            apiResult.setMessage( e.getMessage() );
        } catch (Exception e) {
            log.error( "Fail to login  ", e );
            apiResult.setState( Constants.RESP_STATUS_INTERAL_ERROR );
            apiResult.setMessage( "服务器内部错误" );
        }
        return apiResult;
    }

    @RequestMapping("/sendVerifyCode")
    public ApiResult sendVerifyCode(String phone) {
        ApiResult apiResult = new ApiResult();
        try {
            if (StringUtils.isBlank( phone )) {
                throw new BaseServiceException( "手机号不能为空" );
            }
            userInfoService.sendVerifyCode( phone );
            apiResult.setMessage( "短信验证码发送成功" );
        } catch (Exception e) {
            if (e instanceof BaseServiceException) {
                apiResult.setFailureMessage( e.getMessage() );
            } else {
                apiResult.setFailureMessage( "短信验证码发送失败" );
            }
        }
        return apiResult;
    }
}
